const fs = require("fs");
const FormData = require("form-data");
const https = require("https");
const Promise = require("promise");
const { mkdirs } = require("../common/util");

const POST_URL = "https://2captcha.com/in.php";
const GET_URL =
  "https://2captcha.com/res.php?key=2a52262e19b018b6790edd79ed20dc4d&json=1&action=get&id=";

async function getCaptcha(m, image, today, deviceid, logger) {
  let imgPath = `./captchas/${today}/au/a1`;
  let captchaRes;

  mkdirs(imgPath, function() {
    logger.info("mkdirs success");
  });

  imgPath = `${imgPath}/${deviceid}.png`;

  // 截图
  await shotImage(m, image, imgPath, logger);

  // 读取验证码文件，post请求2captcha，获取id
  logger.info("start post captcha");
  const form = new FormData();

  let parsedData;
  form.append("key", "2a52262e19b018b6790edd79ed20dc4d");
  form.append("file", fs.createReadStream(imgPath));
  form.append("json", 1);
  form.submit(POST_URL, function(err, res) {
    if (err) {
      throw err;
    }
    let rawData = "";
    res.on("data", chunk => {
      rawData += chunk;
    });
    res.on("end", () => {
      if (!res.complete) {
        logger.error("验证码在发送时终止了连接");
      }
      parsedData = JSON.parse(rawData);
      logger.info(captchaRes);

      if (!parsedData.request) {
        logger.error("no request field for captcha response");
        return;
      }

      logger.info(parsedData);
      let p = delay(5 * 1000);
      for (let i = 0; i < 5; ++i) {
        if (captchaRes.request) {
          break;
        }

        captchaRes = p.then(function() {
          console.log("get for captcha");
          if (captchaRes.request) {
            return captchaRes;
          }
          return get(parsedData.request, logger);
        });
      }
    });
  });

  console.log("====================================");
  console.log(captchaRes);
  console.log("====================================");
  // return captchaRes;

  // 每隔5秒get请求一次验证码
  // 5次后终止
  // let t = setInterval(() => {
  //   captchaRes = get(parsedData.request, logger);
  //   if (captchaRes.request) {
  //     logger.info("setInterval has captchaRes");
  //     clearInterval(t);
  //   }
  // }, 5000);

  // setTimeout(() => {
  //   clearInterval(t);
  // }, 25100);
}

function delay(millis) {
  var promise = new Promise(function(resolve) {
    setTimeout(function() {
      resolve();
    }, millis);
  });
  return promise;
}

function get(id, logger) {
  let captchaRes;
  https.get(GET_URL + id, res => {
    let rawData = "";
    res.on("data", chunk => {
      rawData += chunk;
    });
    res.on("end", () => {
      if (!res.complete) {
        res.resume();
        logger.error("验证码在返回时终止了连接");
      }
      captchaRes = JSON.parse(rawData);
      logger.info(captchaRes);
    });
  });

  return captchaRes;
}

async function shotImage(m, image, imgPath, logger) {
  try {
    await image.screenshot({
      path: imgPath,
      omitBackground: true,
      visible: true
    });
    logger.info("screenshot success");
  } catch (e) {
    await m.sleep(2 * 1000);
    logger.info("wait for screenshot");
    logger.info(e);
    await shotImage(m, image, imgPath, logger);
  }
}

module.exports = getCaptcha;
